<template>
    <view :class="uiStyle == 1 ? '' : 'uiStyle'">
        <!-- pages/community1/index.wxml -->
		<view class="head-block" v-if="weixin == 2">
		     <view class="nav-title" :style="'top:10px'"></view>
			 <!-- 返回 -->
			 <view class="icon" @tap="goMy" :style="'top:6px'">
			      <van-icon name="arrow-left" color="#333" size="45rpx" />
			  </view>
		 </view>
        <!-- 这部分用于占位 -->
        <!-- <view style="width: 100%; height: 140rpx"></view> -->
        <view>
            <!-- 新的滚动展示车位及小区一体的页面 -->
            <view class="top-box" v-if="unitSpaceList.length > 0">
                <view class="flex">
                    <view class="top-box-title">我的小区</view>
                    <view class="top-box-text">点击小区名查看上架车位</view>
                </view>
                <view class="top-scroll-box">
                    <scroll-view class="scroll-view-H" :scroll-x="true">
                        <view class="card-item" @tap="gotoCommunity" :data-data="item" :data-id="index" v-for="(item, index) in unitSpaceList" :key="index">
                            <!-- <image src="/assets/img/bgcard.png" class="card-bg"></image> -->

                            <view>
                                <view v-if="item.manageSum > 0" class="manageSum">
                                    当前小区共享车位
                                    <text v-if="item.manageSum > 0" class="text-style">{{ item.manageSum }}</text>
                                </view>
                                <view v-if="item.manageSum == 0" class="manageSum">当前小区暂无分享车位</view>
                                <view class="card-tag-text">
                                    <view class="del-icon" v-if="!projectId" @tap.stop.prevent="delLicense" :data-data="item" :data-id="index">
                                        <image src="../../static/assets/img/shanchu.png"></image>
                                    </view>
                                </view>
                                <image src="../../static/assets/img/xiaoqu03.png" mode="widthFix" class="card-img"></image>
                            </view>

                            <view class="card-text-name">{{ item.parkingName || '' }}</view>
                        </view>
                        <!-- <view class="card-item" bindtap="gotoAdd" style="margin-right:40rpx">
          <image src="/assets/img/bgcard.png" class="card-bg"></image>
          <image src="/assets/img/addCommunity.png" class="card-add-img"></image>
          <view class="card-add-name">申请认证</view>
        </view> -->
                    </scroll-view>
                </view>
            </view>
            <view v-else>
                <view class="no-data" style="margin-top: 200rpx; margin-bottom: 500rpx">
                    <image style="display: block; margin: 0 auto; width: 240rpx; height: 240rpx" src="../../static/assets/img/No-Data2.png" mode="widthFix"></image>
                    <view class="no-data-info" style="margin-top: 35rpx">暂无关联小区，请点击下方添加小区</view>
                </view>
            </view>
            <!-- 老的车位页-展示待审核与审核通过的;若有审核通过的则显示下方按钮 -->
            <view>
                <!-- wx:if="{{status&&type==1}}" -->
                <!-- <view class="body-container">
      <view class="body-banner1">
        <image src='/assets/img/communitybz.png'></image>
        <view class="body-hb body-hb-title">我的小区</view>
        <view class="body-content">
          <view wx:for="{{list}}" wx:key="index">
            <view wx:if="{{item.checkStatus==1}}">
              <view class="body-ha">{{item.name}}（已审核认证）</view>
            </view>
          </view>
          <view wx:for="{{list}}" wx:key="index">
            <view wx:if="{{item.checkStatus==0}}">
              <view class="body-hb">{{item.name}} （系统正在努力审核...）</view>
            </view>
            <view class="body-hb" wx:if="{{item.checkStatus==-1}}">{{item.name}}系统审核不通过</view>
          </view>
        </view>
      </view>
    </view> -->
                <!-- <view class="body-btn-double" wx:if="{{hasCommunity == true}}">
        <view class="body-btn1">
            <van-button type="info" data-key="item" bindtap="handleRelease">
                去发布上架
            </van-button>
        </view>
        <view class="body-btn2">
            <van-button type="info" data-key="item" bindtap="handleCar">查看已发布和收益</van-button>
        </view>
        <view class="body-btn2">
            <van-button type="info" data-key="item" bindtap="inviteVisitor">访客邀请</van-button>
        </view>
        <view class="body-btn2">
            <van-button type="info" data-key="item" bindtap="neighbourParklist">邻里车位</van-button>
        </view>
    </view> -->
                <!-- 新的底部按钮样式 -->
                <view>
                    <view class="btn-row" v-if="!projectId">
                        <view class="btn" @tap="intelligentReservation">添加小区</view>
                        <view class="btn1" v-if="weixin == 2" @tap="inviteVisitor">访客邀请</view>
                    </view>
                </view>
            </view>
            <!-- 下面关联小区功能也统一用上面的新增-关联小区&申请车位二合一 -->
            <!-- <view wx:if="{{!status&&type==1}}">
    <view class="body-container">
        <view class="body-banner">
            <image src='/assets/img/communitybg.png' mode="widthFix"></image>
            <view class="body-h1">邻里共享  互帮互助</view>
            <view class="body-h4">发布车位赚零钱  互帮互助  互惠互利</view>
        </view>
    </view>
    <view class="body-btn-double">
        <view class="body-btn" wx:if="{{type==1}}">
            <van-button type="info" data-key="item" bindtap="handlePopoup">关联小区+</van-button>
            <view class="body-h4">添加小区信息，物业审核后，可参与车位邻里共享</view>
        </view>
    </view>
</view> -->
            <!-- 下面的这部分申请小区已用applyCommunity页面代替 -->
            <!-- <view wx:if="{{type==2}}" class="body-t">
    <view class="body-container">
        <view class="body-banner">
            <view class="body-h1">邻里共享  互帮互助</view>
            <image src='/assets/img/communitybg.png' mode="widthFix"></image>
            <view class="body-h4">您的小区还未加入邻里共享，发起人数达到10人后，我们将和物业协商开通 ！</view>
        </view>
    </view>
    <view class="cm-title">请输入小区名称</view>
    <view class="cm-input">
        <van-field model:value="{{ valueApply }}" border="{{ true }}" placeholder="请输入" />
    </view>
    
</view>
<view class="body-btn" wx:if="{{type==2}}">
    <van-button type="info" data-key="item" bindtap="handleApply">我要申请开通</van-button>
</view> -->
            <!-- 小区选择下拉 -->
            <van-popup v-model="show" position="bottom" @close="onClose">
                <van-picker show-toolbar :columns="columns" @cancel="onCancel" @confirm="onConfirm" @change="onChange" />
            </van-popup>
            <van-dialog id="van-dialog" confirm-button-text="我知道了" confirm-button-color="#00BCAB" />
        </view>
    </view>
</template>

<script>
// pages/community1/index.js
import util from './../../utils/util.js';
import api from './../../utils/api.js';
import { Dialog } from 'vant';
export default {
    data() {
        return {
            allNum: '',
            //邻里车位总数
            status: false,
            //是否关联小区  未关联
            columns: [],
            //checkStatus0:待审核, 1审核通过, -1审核不通过
            list: [],
            //关联小区
            show: false,
            value: '',
            type: 1,
            //默认1 添加小区，2 新增其他小区
            valueApply: '',
            //申请小区
            alert: false,
            //提示
            showbtn: false,
            //体验邻里共享，预约/包月租赁车位
            banner: [],
            hasCommunity: false,
            //审核通过的小区超过1个（含）即为true
            isLogin: false,
            //是否已登录
            unitSpaceList: [],
            //我的小区和车位列表
            marginTopmenuBtn: '', //获取胶囊的初始位置
			weixin:0,
			uiStyle:1,
			weixin:uni.getStorageSync('weixin'),
			projectId:uni.getStorageSync('projectId') || ''
		};
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function () {
		this.uiStyle = uni.getStorageSync('uiStyle') || 1
        // 仅保留在onshow中调用
        // if(wx.getStorageSync('AUTHORIZATION')){
        //   this.getUnitSpaceList();
        //   this.getmyUnitList();
        //   this.getmySpaceList();
        // }
        // 存储当前页面-登陆后跳转至登录前页面
        if (uni.getStorageSync('AUTHORIZATION')) {
            this.setData({
                isLogin: true
            });
        }
		this.weixin = uni.getStorageSync('weixin')
        if (!this.isLogin) {
            this.gotoLogin();
        }

        const page = getCurrentPages();
        uni.setStorageSync('lastPagePath', '/' + page[0].route);
        uni.removeStorageSync('searchHistory');
        uni.removeStorageSync('isSearching'); //查询完就移除掉、
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        if (uni.getStorageSync('AUTHORIZATION')) {
            this.setData({
                isLogin: true
            });
            this.getUnitSpaceList();
            this.getmyUnitList();
            this.getmySpaceList(); // this.getList(); //暂时不需要下拉小区数据
        } else {
            this.setData({
                isLogin: false
            });
        }
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    // onShareAppMessage: function () {},
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */ methods: {
        //选择器
        handlePopoup() {
            this.setData({
                show: true
            });
        },
		goMy() {
		     uni.navigateBack({
		         delta: 1
		     });
		 },
        // 新增--查询我的小区和车位
        getUnitSpaceList() {
            let param = {
                userUnionId: uni.getStorageSync('unionId')
            };
            util.request(api.getUnitspaceList, param, 'GET')
                .then((res) => {
                    if (res.success) {
                        var allNum = '';
                        var arr = [];

                        if (res.data.length > 0) {
                            allNum = 0;
                        }

                        for (var i = 0; i < res.data.length; i++) {
                            if (res.data[i].parkingNumberAuthState == 1 || (res.data[i].parkingNumberAuthState == null && res.data[i].unitAuthStatus == 1)) {
                                if (arr.indexOf(res.data[i].parkingName) == -1) {
                                    arr.push(res.data[i].parkingName);
                                    allNum = parseInt(allNum) + res.data[i].manageSum;
                                }
                            }
                        } // console.log(arr)

                        console.log(allNum);
                        this.setData({
                            allNum: allNum
                        });
                        this.setData({
                            unitSpaceList: res.data
                        });
                    } else {
                        uni.showToast({
                            title: res.msg || '接口出错了...',
                            icon: 'none'
                        });
                    }
                })
                .catch((err) => {
                    console.log(err);
                    uni.showToast({
                        title: '接口出错了',
                        icon: 'none'
                    });
                });
        },

        goBack() {
            uni.switchTab({
                url: '../home/index'
            });
        },

        //申请小区
        // handleApply() {
        //   if (this.data.valueApply != '') {
        //     Dialog.alert({
        //       message: '收到您的申请，我们将会把您的申请反馈给小区物业及业主委员会，请耐心等待',
        //     }).then(() => {
        //       this.getcommitMyUnit()
        //     })
        //   } else {
        //     wx.showToast({ title: '请输入关联小区名称', icon: 'none' })
        //   }
        // },
        //查看已发布车位
        handleCar() {
            if (!this.hasCommunity) {
                uni.showToast({
                    title: '请先认证小区和车位信息',
                    icon: 'none'
                });
                return;
            }

            if (this.banner.length > 0) {
                uni.navigateTo({
                    url: '../communityOrder/index'
                });
            } else {
                uni.showToast({
                    title: '暂无发布的车位',
                    icon: 'none'
                });
            }
        },

        onClose() {
            this.setData({
                show: false
            });
        },

        onChange(event) {
            const { picker, value, index } = event.detail;
            console.log(picker, value, index); // Toast(`当前值：${value}, 当前索引：${index}`);
        },

        // 下拉框选择
        // onConfirm(e) {
        //   console.log(e)
        //   if (e.detail.value.text === '其他') {
        //     this.setData({
        //       type: 2,
        //     })
        //   } else {
        //     this.getcommitMyUnit(e.detail.value.unitCode)
        //   }
        //   this.setData({ show: false })
        // },
        onCancel() {
            this.setData({
                show: false
            });
        },

        //查询小区下拉
        getList() {
            const param = {
                communityCode: '111',
                unitName: '',
                isOpen: 1,
                pageInfo: {
                    pageNumber: 1,
                    pageSize: 100
                }
            };
            util.request(api.list, param, 'POST').then((res) => {
                if (res.code == 0) {
                    var array = [];

                    if (res.data.content) {
                        res.data.content.map((e, index) => {
                            array.push(
                                Object.assign({}, e, {
                                    text: e.unitName
                                })
                            );
                        });
                    }

                    array.push({
                        text: '其他'
                    });
                    this.setData({
                        columns: array
                    });
                }
            });
        },

        //查询关联小区
        getmyUnitList() {
            const unionId = uni.getStorageSync('unionId') || '';
            util.request(api.myUnitList + '?unionId=' + unionId, 'get').then((res) => {
                // console.log(res);
                if (res.code == 0) {
                    if (res.data.length > 0) {
                        if (res.data.find((e) => e.checkStatus == 1)) {
                            this.setData({
                                showbtn: true
                            });
                        }

                        this.setData({
                            list: res.data,
                            status: true
                        });

                        if (res.data.find((e) => e.checkStatus === 0)) {
                            this.setData({
                                alert: true
                            });
                        }

                        if (res.data.find((e) => e.checkStatus == 1)) {
                            this.setData({
                                hasCommunity: true
                            });
                        }
                    }
                }
            });
        },

        //申请关联小区
        // getcommitMyUnit(data) {
        //   const unionId = wx.getStorageSync('unionId') || ''
        //   if (this.data.type === 2) {
        //     util
        //       .request(
        //         api.commitMyUnit + '?userUnionId=' + unionId + '&applyUnitName=' + this.data.valueApply,
        //         'get'
        //       )
        //       .then(res => {
        //         if (res.code == 0) {
        //           wx.showToast({ title: '申请成功', icon: 'success' })
        //           this.getmyUnitList()
        //           this.setData({
        //             type: 1,
        //           })
        //         } else {
        //           wx.showToast({ title: res.msg })
        //         }
        //       })
        //   } else {
        //     util.request(api.commitMyUnit + '?userUnionId=' + unionId + '&unitCode=' + data, 'get').then(res => {
        //       if (res.code == 0) {
        //         this.getmyUnitList()
        //         this.setData({
        //           type: 1,
        //         })
        //         wx.showToast({ title: '申请成功', icon: 'success' })
        //       } else {
        //         wx.showToast({ title: res.msg })
        //       }
        //     })
        //   }
        // },
        // 查询我的车位--数据在发布上架时用到
        getmySpaceList() {
            const unionId = uni.getStorageSync('unionId') || '';
            util.request(api.mySpaceList + '?userUnionId=' + unionId, 'get').then((res) => {
                if (res.code == 0) {
                    this.setData({
                        banner: res.data
                    });
                }
            });
        },

        handleRelease() {
            if (!this.hasCommunity) {
                uni.showToast({
                    title: '请先认证小区和车位信息',
                    icon: 'none'
                });
                return;
            }

            if (this.banner.length > 0 && this.banner.find((e) => (e.authStatus = 1))) {
                const value = 2;
                uni.navigateTo({
                    url: '../setParking1/index?active=' + value
                });
            } else if (this.banner.length > 0 && this.banner.find((e) => (e.authStatus = -1))) {
                uni.showToast({
                    title: '抱歉，您的车位状态异常，请到物业中心处理。',
                    icon: 'none'
                });
            } else {
                uni.showToast({
                    title: '抱歉，系统未查询到您的车位，请到物业中心确认和添加',
                    icon: 'none'
                });
            }
        },

        handleOrder() {},

        gotoLogin() {
            uni.navigateTo({
                url: '../login/index'
            });
        },

        gotoAdd() {
            uni.navigateTo({
                url: '../applyStep1/applyStep1'
            });
        },

        inviteVisitor() {
            if (!this.hasCommunity) {
                uni.showToast({
                    title: '请先认证小区和车位信息',
                    icon: 'none'
                });
                return;
            }
			if(uni.getStorageSync('weixin') == 2){
				jWeixin.miniProgram.navigateTo({
					url: "/pages/visitors/visitors?unionId=" + uni.getStorageSync('unionId') + '&token=' + uni.getStorageSync('AUTHORIZATION')
				})
			}else{
				uni.navigateTo({
					url: '../inviteVisitor/inviteVisitor'
				});		
			}

        },

        gotoCommunity(e) {
            let { parkingCode } = e.currentTarget.dataset.data;
            uni.navigateTo({
                url: '../newParklist/newParklist?parkingcode=' + parkingCode + '&active=0'
            });
        },

        // 邻里车位
        neighbourParklist() {
            if (!this.hasCommunity) {
                uni.showToast({
                    title: '请先认证小区和车位信息',
                    icon: 'none'
                });
                return;
            }

            uni.navigateTo({
                url: '../newParklist/newParklist?parkingcode=' + parkingcode + '&active=' + (this.carType == 'month' ? '1' : '0')
            });
        },

        intelligentReservation() {
            uni.navigateTo({
                url: '../community2/index'
            });
        },

        delLicense(e) {
            let that = this;
            let delLicense = e.currentTarget.dataset.data;
            console.log(e.currentTarget.dataset.data);
            Dialog.confirm({
                context: this,
                message: '确定删除' + delLicense.parkingName + '？'
            })
                .then(() => {
                    // on confirm
                    uni.showLoading({
                        title: '删除中，请稍后！'
                    });
                    that.whitelist(delLicense.parkingCode);
                })
                .catch(() => {
                    // on cancel
                });
        },

        whitelist(data) {
            const unionId = uni.getStorageSync('unionId') || '';
            let that = this;
            util.request(api.whitelist + '?unionId=' + unionId + '&parkingCode=' + data, 'get') //
                .then((res) => {
                    if (res.code == 0) {
                        that.getUnitSpaceList();
                        uni.hideLoading();
                        uni.showToast({
                            title: '删除成功',
                            icon: 'success',
                            duration: 1000
                        });
                    } else {
                        uni.hideLoading();
                        uni.showToast({
                            title: res.msg,
                            duration: 1000
                        });
                    }
                });
        },

        onConfirm() {
            console.log('占位：函数 onConfirm 未声明');
        }
    }
};
</script>
<style>
@import './index.css';
</style>
